<template>
  <div class="container">
    <el-card class="box-card ">
      <div class="content">
        <div class="left">
          <el-row type="flex"
                  align="middle">
            <el-col :span="25">
              <el-input size="small"
                        v-model="filterText"
                        prefix-icon="el-icon-search"
                        placeholder="请输入部门名称"></el-input>
            </el-col>
          </el-row>
          <el-tree class="filter-tree"
                   :data="deptList"
                   @node-click="nodechage"
                   :props="defaultProps"
                   default-expand-all
                   :filter-node-method="filterNode"
                   ref="tree">
          </el-tree>
        </div>
        <div class="right">
          <el-row :gutter="8"
                  type="flex"
                  align="middle"
                  style="margin-bottom:10px">
            <el-col :span="1.5">
              用户名称
            </el-col>
            <el-col :span="40">
              <el-input size="small"
                        v-model="queryParams.userName"
                        placeholder="请输入用户名称"></el-input>
            </el-col>
            <el-col :span="1.5">
              手机号码
            </el-col>
            <el-col :span="40">
              <el-input size="small"
                        v-model="queryParams.phonenumber"
                        style="width: 200px"
                        placeholder="请输入手机号码"></el-input>
            </el-col>

          </el-row>

          <el-row :gutter="8"
                  type="flex"
                  align="middle"
                  size="small"
                  style="margin-bottom:10px;margin-top:20px">
            <el-col :span="1.5">
              状态
            </el-col>
            <el-col :span="40">
              <el-select placeholder="请选择"
                         size="small"
                         v-model="queryParams.status">

                <el-option label="正常"
                           :value="0">
                </el-option>
                <el-option label="停用"
                           :value="1">
                </el-option>

              </el-select>

            </el-col>
            <el-col :span="1.5">
              创建时间
            </el-col>
            <el-col :span="30">
              <el-date-picker type="daterange"
                              size="small"
                              style="width:200px"
                              range-separator="至"
                              value-format="yyyy-MM-dd"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
            <el-col :span="1.5">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-search"
                         @click="getData()">搜索</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button icon='el-icon-refresh'
                         size="mini"
                         @click="refreshTable()">重置</el-button>
            </el-col>
          </el-row>
          <div class="btnList">
            <el-row :gutter="8"
                    type="flex"
                    align="middle"
                    class="btn_nav">
              <el-col :span="1.5">
                <el-button size="mini"
                           type="primary"
                           icon="el-icon-plus"
                           plain
                           @click="addXqq">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button size="mini"
                           type="success"
                           icon="el-icon-edit"
                           plain
                           @click="updatadata"
                           :disabled='checkItem.length!=1'>修改</el-button>
              </el-col>

              <el-col :span="1.5">
                <el-button size="mini"
                           type="danger"
                           icon="el-icon-delete"
                           plain
                           :disabled='checkItem.length==0'
                           @click="delMore">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button size="mini"
                           type="info"
                           icon="el-icon-upload2"
                           plain
                           @click="impt">导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button size="mini"
                           type="warning"
                           icon="el-icon-download"
                           @click="exportdata"
                           plain>导出</el-button>
              </el-col>
            </el-row>

            <el-row :gutter="8"
                    type="flex"
                    align="middle"
                    class="btn_nav">

              <el-col :span="1.5">
                <el-button size="mini"
                           icon="el-icon-search"
                           circle></el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button @click="refreshTable"
                           size="mini"
                           icon="el-icon-refresh"
                           circle></el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button @click="disenables"
                           size="mini"
                           icon="el-icon-menu"
                           circle></el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="tableData"
                    v-loading="loading"
                    style="width: 100%"
                    :header-cell-style="{background:'#f8f8f9','text-align':'center'}"
                    @selection-change="handleSelectionChange"
                    :cell-style="{'text-align':'center'}">
            <el-table-column type="selection">
            </el-table-column>
            <el-table-column v-if="columnToggle[0].flag"
                             prop="userId"
                             label="用户编号">
            </el-table-column>
            <el-table-column prop="userName"
                             v-if="columnToggle[1].flag"
                             label="用户名称">
            </el-table-column>
            <el-table-column prop="nickName"
                             v-if="columnToggle[2].flag"
                             label="用户昵称">
            </el-table-column>

            <el-table-column prop="dept.deptName"
                             v-if="columnToggle[3].flag"
                             label="部门">

            </el-table-column>
            <el-table-column prop="phonenumber"
                             v-if="columnToggle[4].flag"
                             label="手机号码">
            </el-table-column>
            <el-table-column prop="status"
                             v-if="columnToggle[5].flag"
                             label="状态">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.status"
                           @change="changeStatus($event,scope.row)"
                           inactive-value="1"
                           active-value="0">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="createTime"
                             v-if="columnToggle[6].flag"
                             label="创建时间">
            </el-table-column>

            <el-table-column label="操作">
              <template v-slot="data">
                <el-button icon="el-icon-edit"
                           type="text"
                           @click="updateHandler(data.row.userId)">修改</el-button>
                <el-button v-if="data.row.userId!=1"
                           icon="el-icon-delete"
                           type="text"
                           @click="deleteHandler(data.row.userId)">删除</el-button>
                <el-button icon="el-icon-delete"
                           type="text"
                           @click="resetpassword(data.row.userId,data.row.userName)">重置</el-button>
              </template>

            </el-table-column>

          </el-table>
          <div class="page"
               v-show="total!=0">
            <el-pagination background
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="queryParams.pageNum"
                           :page-sizes="[3, 5, 7, 9]"
                           :page-size="queryParams.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="total">
            </el-pagination>
          </div>
        </div>
        <div>
          <el-dialog :title="flag?'添加用户':'修改用户'"
                     :visible.sync="dialogVisible"
                     width="50%">
            <el-form :model="formData"
                     ref="ruleForm"
                     label-width="120px">
              <div style="display:flex;justify-content:space-between;align-items:center;">
                <el-form-item label="用户昵称">
                  <el-input size="small"
                            v-model="formData.nickName"
                            placeholder="请输入用户昵称"></el-input>
                </el-form-item>
                <el-form-item label="归属部门">
                  <el-select v-model="form.id"
                             placeholder="请选择"
                             ref="selectTree">
                    <el-option :label="form.value"
                               :value="form.id"
                               hidden>
                    </el-option>
                    <el-tree :data="deptList"
                             :props="defaultProps"
                             node-key="id"
                             accordion
                             highlight-current
                             @node-click="handleNodeClick" />
                  </el-select>

                </el-form-item>
              </div>
              <div style="display:flex;justify-content:space-between">
                <el-form-item label="手机号码">
                  <el-input size="small"
                            v-model="formData.phonenumber"
                            placeholder="请输入手机号码"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input size="small"
                            v-model="formData.email"
                            placeholder="请输入邮箱"></el-input>
                </el-form-item>
              </div>
              <div style="display:flex;justify-content:space-between">
                <el-form-item label="用户名称">
                  <el-input size="small"
                            v-model="formData.userName"
                            placeholder="请输入用户名称"></el-input>
                </el-form-item>
                <el-form-item v-if="flag"
                              label="用户密码">
                  <el-input size="small"
                            v-model="initpassword"
                            type="password"
                            placeholder="请输入用户密码"></el-input>
                </el-form-item>
              </div>
              <div style="display:flex;justify-content:space-between">
                <el-form-item label="用户性别">
                  <el-select size="small"
                             v-model="formData.sex"
                             placeholder="请选择">

                    <el-option v-for="(el,index) in sexlist"
                               :key="index"
                               :label="el.dictLabel"
                               :value="el.dictValue">
                    </el-option>

                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <template>
                    <el-radio v-model="formData.status"
                              label="0">正常</el-radio>
                    <el-radio v-model="formData.status"
                              label="1">停用</el-radio>
                  </template>
                </el-form-item>
              </div>
              <div style="display:flex;justify-content:space-between">
                <el-form-item label="岗位">
                  <el-select multiple
                             size="small"
                             v-model="formData.postIds"
                             placeholder="请选择">

                    <el-option v-for="el in posts"
                               :key="el.postId"
                               :label="el.postName"
                               :value="el.postId">
                    </el-option>

                  </el-select>
                </el-form-item>
                <el-form-item label="角色">
                  <el-select multiple
                             size="small"
                             v-model="formData.roleIds"
                             placeholder="请选择">

                    <el-option v-for="el in roles"
                               :key="el.roleId"
                               :label="el.roleName"
                               :value="el.roleId">
                    </el-option>

                  </el-select>
                </el-form-item>
              </div>
              <el-form-item label="备注">
                <el-input size="small"
                          type="textarea"
                          v-model="formData.remark"
                          placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer"
                  class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary"
                         @click="update">确 定</el-button>
            </span>
          </el-dialog>
        </div>

        <div>
          <el-dialog title="提示"
                     :visible.sync="pwd"
                     @closed="closedpwd"
                     width="30%">
            <el-row style="margin-bottom:10px">请输入{{resetUser}}的新密码</el-row>
            <el-input placeholder="请输入密码"
                      v-model="password"
                      show-password></el-input>
            <span slot="footer"
                  class="dialog-footer">
              <el-button @click="pwd = false">取 消</el-button>
              <el-button type="primary"
                         @click="toreset">确 定</el-button>
            </span>
          </el-dialog>
        </div>

        <div>
          <el-dialog :title="importFlag?'用户导入':'结果'"
                     :visible.sync="imt"
                     @closed="closedpwd"
                     width="30%">
            <div v-if="importFlag">
              <el-upload style="margin:0 auto;margin-bottom:10px"
                         ref="upload"
                         show-file-list
                         class="upload-demo"
                         :auto-upload="false"
                         :limit="1"
                         :on-change="bfupload"
                         :on-remove="onremove"
                         drag
                         :file-list="file"
                         action="https://jsonplaceholder.typicode.com/posts/">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

                <div class="el-upload__tip"
                     style="color:red"
                     slot="tip">
                  <el-checkbox v-model="updateSupport">是否更新已经存在的用户数据 <el-link type="info"
                             @click="getExport()">下载模板</el-link>
                  </el-checkbox><br>
                  提示：仅允许导入“xls”或“xlsx”格式文件！
                </div>

              </el-upload>
              <span slot="footer"
                    class="dialog-footer">
                <el-button @click="imt = false">取 消</el-button>
                <el-button type="primary"
                           @click="toimport">确 定</el-button>
              </span>
            </div>
            <div v-if="!importFlag">
              <span slot="footer"
                    class="dialog-footer">
                <div v-html="uploadmsg"></div>
                <el-button type="primary"
                           @click="imt=false">确 定</el-button>
              </span>
            </div>

          </el-dialog>
        </div>

      </div>
    </el-card>
    <div>
      <el-dialog title="显示与隐藏"
                 :visible.sync="disNone"
                 width="50%">
        <el-transfer :titles="['显示','隐藏']"
                     v-model="value"
                     :data="columnToggle"></el-transfer>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
  data() {
    return {
      value: [],
      disNone: false,
      uploadmsg: '',
      file: [],
      updateSupport: false,
      imt: false,
      importFlag: true,
      userId: '',
      pwd: false,
      resetUser: '',
      password: '',
      form: {
        id: '',
        value: ''
      },
      flag: false,
      dialogVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        userName: null,
        phonenumber: null,
        status: null
        // beginTime: '',
        // endTime: ''
        // params: { beginTime: '', endTime: '' }
      },

      seltime: null,
      total: 0,
      loading: false,
      checkItem: [],
      filterText: '',
      deptList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableData: [],
      formData: {
        deptId: null,
        email: null,
        nickName: null,
        password: null,
        phonenumber: null,
        postIds: null,
        remark: null,
        roleIds: [],
        sex: null,
        status: '0',
        userName: '',
        userId: null
      },
      posts: [],
      roles: [],
      sexlist: [],
      initpassword: '',
      columnToggle: [
        { key: nanoid(), label: '用户编号', disabled: false, flag: true },
        { key: nanoid(), label: '用户名称', disabled: false, flag: true },
        { key: nanoid(), label: '用户昵称', disabled: false, flag: true },
        { key: nanoid(), label: '部门', disabled: false, flag: true },
        { key: nanoid(), label: '手机号码', disabled: false, flag: true },
        { key: nanoid(), label: '状态', disabled: false, flag: true },
        { key: nanoid(), label: '创建时间', disabled: false, flag: true }
      ]
    }
  },
  mounted() {
    this.getDeptList()
    this.getData()
    this.initPassword()
    this.initsex()
  },
  methods: {
    // 树形菜单

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    //
    disenables() {
      this.disNone = true
    },
    // 获取数据{

    async getDeptList() {
      let { data } = await this.$axios.get('system/dept/treeselect')
      this.deptList = data.data
    },
    async initsex() {
      let { data } = await this.$axios.get('system/dict/data/type/sys_user_sex')
      this.sexlist = data.data
    },
    async initPassword() {
      let { data } = await this.$axios.get('system/config/configKey/sys.user.initPassword')
      this.initpassword = data.msg
    },
    async getData() {
      this.loading = true
      let { data } = await this.$axios.get('system/user/list', { params: this.queryParams })
      this.tableData = data.rows
      this.total = data.total
      this.loading = false
    },

    //改变状态system/user/changeStatus

    changeStatus(status, data) {
      this.$confirm(`确认要${status == 0 ? '启用' : '停用'}${data.userName}用户吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$axios.put(`system/user/changeStatus`, { status: status, userId: data.userId })

          if (res.code != 200) {
            this.$message.error(res.msg)
            this.getData()
          } else {
            this.$message.success(res.msg)
            this.getData()
          }
        })
        .catch(() => {
          this.getData()
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 左侧节点
    nodechage(data) {
      this.queryParams.deptId = data.id
      this.getData()
    },

    async getUser() {
      let { data } = await this.$axios.get('system/user/')
      this.posts = data.posts
      this.roles = data.roles
    },
    // 归属部门
    handleNodeClick(data) {
      this.form = {
        id: data.id,
        value: data.label
      }

      // 使 input 失去焦点，并隐藏下拉框
      this.$refs.selectTree.blur()
    },

    updatadata() {
      this.tip = false
      this.updateHandler(this.checkItem[0].userId)
    },
    delMore() {
      let ids = this.checkItem.map((el) => el.userId)
      this.deleteHandler(ids)
    },
    deleteHandler(id) {
      this.$confirm(`是否确认删除编号为${id.toString()}的数据项?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let data = await this.$axios.delete(`system/user/${id.toString()}`)
          console.log(data)
          if (data.data.code != 200) this.$message.error(data.data.msg)
          this.$message({
            type: 'success',
            message: data.data.msg
          })
          this.getData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    async updateHandler(id) {
      this.flag = false
      this.dialogVisible = true
      this.getUser()
      let { data } = await this.$axios.get(`system/user/${id}`)
      this.formData = data.data
      this.formData.roleIds = data.roleIds
      this.formData.postIds = data.postIds
      this.form.value = data.data.dept.deptName
      this.form.id = data.deptId
      this.roles = data.roles
      this.posts = data.posts
    },

    async update() {
      this.formData.deptId = this.form.id
      let data = null
      this.dialogVisible = false

      if (this.formData.userId) {
        data = await this.$axios.put('system/user', this.formData)
      } else {
        data = await this.$axios.post('system/user', this.formData)
      }

      if (data.data.code != 200) return this.$message.error(data.data.msg)
      this.$message({ type: 'success', message: data.data.msg })
      this.getData()
    },

    addXqq() {
      this.getUser()
      this.flag = true
      this.dialogVisible = true
      this.form = {
        id: null,
        value: null
      }
      this.formData = { deptId: null, email: null, nickName: null, password: null, phonenumber: null, postIds: null, remark: null, roleIds: [], sex: null, status: '0', userName: '' }
    },
    closedpwd() {
      this.password = null
      this.pwd = false
    },
    async resetpassword(id, userName) {
      this.pwd = true
      this.resetUser = userName
      this.userId = id
    },
    async toreset() {
      let { data } = await this.$axios.put('system/user/resetPwd', { password: this.password, userId: this.userId })
      this.pwd = false
      if (data.code != 200) return this.$message.error(data.msg)
      this.$message.success(data.msg + '您的新密码是' + this.password)
      this.getData()
    },
    // 刷新
    // 刷新
    refreshTable() {
      this.loading = true
      this.getData()
      this.queryParams = { pageNum: 1, pageSize: 10, deptId: null, userName: null, phonenumber: null, status: null }
    },

    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getData()
    },
    handleSelectionChange(val) {
      this.checkItem = val
    },
    async exportdata() {
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // let data = await this.$axios.get('system/user/export', { params: this.queryParams })
          // console.log(data)
          this.getExport()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    async getExport() {
      let { data } = await this.$axios.get('system/user/export', { params: this.queryParams })

      if (data.code != 200) {
        this.$message.error('失败')
      } else {
        window.location.href = 'https://jumeng.xzjumeng.com/prod-api/common/download?fileName=' + encodeURI(data.msg) + '&delete=' + true
      }
    },
    // 导入
    impt() {
      this.importFlag = true
      this.imt = true
    },
    bfupload(file, fileList) {
      this.file = fileList
    },
    onremove() {
      this.file = []
    },
    async toimport() {
      if (this.file.length < 1) return this.$message.error('请选择文件')
      let formData = new FormData()
      formData.append('file', this.file[0].raw)
      let { data } = await this.$axios.post('system/user/importData?updateSupport=' + this.updateSupport, formData)
      this.importFlag = false
      this.uploadmsg = data.msg
      this.$refs.upload.clearFiles()
      this.file = []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    seltime(val) {
      if (val == null) {
      } else {
        // this.queryParams.params[beginTime] = val[0]
        // this.queryParams.params[endTime] = val[1]
        // console.log(this.queryParams.beginTime)
      }
    },
    // 监听隐藏的内容
    value(val) {
      this.columnToggle.forEach((e, i) => {
        if (val.indexOf(e.key) != -1) {
          e.flag = false
        } else {
          e.flag = true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  .left {
    padding-left: 10px;
    padding-right: 10px;
    width: 14%;
  }
  .right {
    width: 85%;
  }

  .el-card__body {
    padding: 10px;
    padding-top: 20px;
    .btnList {
      margin-bottom: 8px;
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
    }
    .page {
      margin-top: 15px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>